package info.fastpace.utils.iterator;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

public class ConsecutiveIterator<E> implements Iterator<E> {
	private List<Iterator<E>> iterators = new ArrayList<Iterator<E>>();
	private int nextIteratorIndex = 0;
	private Iterator<E> subIterator = null;

	public ConsecutiveIterator() {
		super();
	}
	
	@Override
	public boolean hasNext() {
		// Continue trying to initialize subiterator
		while (subIterator == null || !subIterator.hasNext()) {
			if (nextIteratorIndex >= iterators.size()) {
				// No more iterator - finish
				return false;
			}
			subIterator = iterators.get(nextIteratorIndex++);
		}

		return true;
	}
	
	public void addAll(List<Iterator<E>> iterators) {
		this.iterators.addAll(iterators);
	}
	
	public void add(Iterator<E> iterator) {
		this.iterators.add(iterator);
	}
	
	@Override
	public final E next() {
		if (!hasNext()) {
			throw new NoSuchElementException("No more elements");
		}

		return subIterator.next();
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException("Remove method not supported");
	}

}
